import app from "../vue";
import {ElMessage} from 'element-plus'

import {createRouter, createWebHistory} from 'vue-router'

import {useAdminStore} from '@/dt-lib/plug/pinia/stores/admin'
import {useRouterStore} from '@/dt-lib/plug/pinia/stores/router'

import routes from "./routes";

export const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: routes,
})

export const loginRouter: String = 'login'

const controlRouter: String = 'home'

const adminStore = useAdminStore()

const routerStore = useRouterStore()

// 路由守卫
router.beforeEach(async (to, from) => {

    const isAuthenticated = adminStore.getAdmin.token ? true : false

    if (to.meta.requiresAuth === true) {
        // 检查用户是否已登录 && 避免无限重定向
        if (!isAuthenticated && to.name !== loginRouter) {
            ElMessage.warning('身份已过期，请重新登陆');
            return {name: loginRouter}
        }
    }

    if (to.name === loginRouter) {
        // 如果在登陆页，已登陆直接跳到后台首页
        if (isAuthenticated) {
            return {name: controlRouter}
        }
    }

    routerStore.pushHistory(to)
    // console.log(to)

})


app.use(router)
